# coding: utf-8

from PyQt5 import QtCore
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from app.common.get_version import MinecraftVersionFetcher

from qfluentwidgets import (
    InfoBar,
    InfoBarPosition,
    SegmentedWidget,
    FluentIcon,
    ScrollArea,
    ExpandLayout,
    CardWidget,
    ComboBox,
    BodyLabel,
)
from app.components.versionCard import VersionCard


# 版本滚动区域
class DownloadScrollArea(ScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.widgets = QWidget(self)
        self.layouts = QVBoxLayout(self.widgets)
        self.layouts.setContentsMargins(0, 5, 0, 5)

        self.__initWidget()

    def __initWidget(self):
        self.resize(1000, 800)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setStyleSheet("background:transparent;" "border-radius:10px")

        self.setWidget(self.widgets)
        self.setWidgetResizable(True)
        self.setObjectName("downloadJava")

        # 初始化样式表
        self.widgets.setObjectName("scrollWidget")
        self.widgets.setStyleSheet("QWidget{background:transparent}")

    def addCard(self, widget):
        self.layouts.addWidget(widget, 0, Qt.AlignmentFlag.AlignTop)

    def removeAllCards(self):
        # 遍历布局中的所有项
        for i in reversed(range(self.layouts.count())):
            # 获取布局中的子项
            widget_item = self.layouts.itemAt(i)
            widget = widget_item.widget()

            # 如果是QWidget，就从布局中移除并删除
            if widget:
                self.layouts.removeWidget(widget)
                widget.deleteLater()


# 顶部选择框
class TopSelectorCard(CardWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.sourceLabel = BodyLabel(self)
        self.sourceSelectComboBox = ComboBox(self)
        self.versionLabel = BodyLabel(self)
        self.versionSelectComboBox = ComboBox(self)

        self.releaseVersions = []
        self.snapshotVersions = []
        self.oldVerison = []

        self.__initWidget()

    def __initWidget(self):
        self.sourceLabel.setText(
            self.tr(
                "Please select you download source(look forward to other sources)"
            )
        )
        self.sourceSelectComboBox.addItems(
            [self.tr("Official source")]
        )

        self.versionLabel.setText(self.tr("Version screening"))
        self.versionSelectComboBox.addItems(
            [
                self.tr("Release version"),
                self.tr("Snapshot version"),
                self.tr("Old edition"),
            ]
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QHBoxLayout(self)
        self.layouts.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.layouts.addWidget(self.sourceLabel)
        self.layouts.addWidget(self.sourceSelectComboBox)

        self.layouts.addSpacing(100)

        self.layouts.addWidget(self.versionLabel)
        self.layouts.addWidget(self.versionSelectComboBox)

    def addVersion(self, dict):
        self.releaseVersions = dict["release"]
        self.snapshotVersions = dict["snapshot"]
        self.oldVerison = dict["old"]


# 主界面
class GameInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        # 定义pivot小部件
        self.pivot = SegmentedWidget(self)

        # 定义顶部选择框
        self.topSelectorCard = TopSelectorCard(self)

        # 定义滚动区域
        self.downloadArea = DownloadScrollArea(self)

        # 提示用户不提供开始游戏的能力
        self.waringInfoBar = InfoBar.warning(
            title=self.tr("tips"),
            content=self.tr(
                "Piebox in game only to provide assistance, do not provide startup function, please understand.\nAnd interface is still under development."
            ),
            orient=Qt.Horizontal,
            isClosable=True,
            duration=-1,
            position=InfoBarPosition.TOP_LEFT,
            parent=self,
        )

        self.__initWidget()
        self.__initVersion()

    def __initWidget(self) -> None:
        self.resize(1000, 800)
        self.setObjectName("gameInterface")

        # 添加枢轴项目
        self.pivot.addItem(
            routeKey="downloadJava",
            text=self.tr("download game"),
            icon=FluentIcon.DOWNLOAD,
        )
        self.pivot.addItem(
            routeKey="gameAssist",
            text=self.tr("tool of minecraft(developing)"),
            icon=FluentIcon.CLOUD,
        )
        self.pivot.setCurrentItem("downloadJava")

        self.topSelectorCard.versionSelectComboBox.currentIndexChanged.connect(self._changeVersionList)

        self.__initLayout()

    def __initLayout(self) -> None:
        self.layouts = QVBoxLayout(self)
        self.layouts.setSpacing(5)
        self.layouts.setContentsMargins(5, 10, 5, 5)

        self.layouts.addWidget(self.pivot, 0, Qt.AlignmentFlag.AlignTop)
        self.layouts.addWidget(self.topSelectorCard, 0, Qt.AlignmentFlag.AlignTop)
        self.layouts.addWidget(self.downloadArea)

    def __initVersion(self):
        versionGetThread = MinecraftVersionFetcher()
        versionGetThread.versionsDict.connect(
            lambda dict: self.topSelectorCard.addVersion(dict)
        )
        versionGetThread.finished.connect(lambda: self._changeVersionList(0))
        versionGetThread.start()
        versionGetThread.wait()


    def _changeVersionList(self, index):
        if index == 0:
            versionsList = self.topSelectorCard.releaseVersions
        elif index == 1:
            versionsList = self.topSelectorCard.snapshotVersions
        else:
            versionsList = self.topSelectorCard.oldVerison

        self.downloadArea.removeAllCards()
        for version in versionsList:
            card = VersionCard(
                self.downloadArea.widgets,
                version["id"],
                version["type"],
                version["url"],
            )
            self.downloadArea.addCard(card)
